import {reqGetCartList,reqDeleteCartById,reqUpdateCheckedById} from '@/api'
const state = {
    cartList:[]
}
const mutations = {
    GETCARTLIST(state,cartList){
        state.cartList = cartList;
    }
}
const actions = {
    //获取购物车列表数据
    async getCartList({commit}){
        let result = await reqGetCartList();
        // console.log(result);
        if (result.code == 200) {
            commit('GETCARTLIST',result.data);
        }
    },
    //删除购物车某个产品
    async deleteCartById({commit},skuId){
        let result = await reqDeleteCartById(skuId);
        console.log(result);
        if (result.code == 200) {
            return '购物车数据删除成功';
        } else return Promise.reject(new Error('购物车数据删除失败'));
    },
    //修改购物车某一个产品的选中状态
    async updateCheckedById({commit},{skuId,isChecked}){
        let result = await reqUpdateCheckedById(skuId,isChecked);
        if (result.code == 200) {
            return "修改成功";
        } else return Promise.reject(new Error('修改失败'))
    },
    //删除选中商品
    deleteAllCheckedCart({dispatch,getters}){
        let PromiseAll = [];
        getters.cartList.cartInfoList.forEach(item=>{
            // item.isChecked==1 && dispatch('deleteCartListBySkuId',item.skuId);
            let promise = item.isChecked==1?dispatch('deleteCartById',item.skuId):'';
            PromiseAll.push(promise);
        })
        return Promise.all(PromiseAll);
    },
    //修改全部产品状态
    updateAllCartChecked({dispatch,state},isChecked){
        let promiseAll = [];
        state.cartList[0].cartInfoList.forEach(item=>{
            let promise = dispatch('updateCheckedById',{skuId:item.skuId,isChecked});
            promiseAll.push(promise);
        });
        return Promise.all(promiseAll);
    }
}
const getters = {
    cartList(state){
        return state.cartList[0]||{};
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}